package com.itheima.app.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.autoconfig.oss.OssTemplate;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.Comment;
import com.itheima.domain.mongo.FocusUser;
import com.itheima.domain.mongo.Video;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.CommentService;
import com.itheima.service.mongo.FocusUserService;
import com.itheima.service.mongo.VideoService;
import com.itheima.utils.ConstantUtil;
import com.itheima.utils.DateFormatUtil;
import com.itheima.vo.CommentVo;
import com.itheima.vo.PageBeanVo;
import com.itheima.vo.VideoVo;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Guanxing
 * @date 2021/9/27
 */
@Component
public class VideoManager {

    @Reference
    private VideoService videoService;

    @Reference
    private UserInfoService userInfoService;

    @Reference
    private FocusUserService focusUserService;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private FdfsWebServer webServer; //上传的服务器 此处红线是idea编译器的问题 能正常使用

    @Autowired
    private FastFileStorageClient client; // 使用的客户端  此处红线是idea编译器的问题 能正常使用

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Reference
    private CommentService commentService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private VideoMQManager videoMQManager;

    //查询小视频列表
    public PageBeanVo findSmallVideos(Integer page, Integer pageSize) {
        //获得当前用户id
        Long loginUserId = UserHolder.getId();
        //查询pageBean
        PageBeanVo pageBeanVo = videoService.findSmallVideos(page, pageSize, loginUserId);

        List<Video> items = (List<Video>) pageBeanVo.getItems();
        List<VideoVo> videoVoList = new ArrayList<>();

        //数据搬家
        if (CollectionUtil.isNotEmpty(items)) {
            for (Video video : items) {
                //查询用户信息
                UserInfo userInfo = userInfoService.findById(video.getUserId());
                //创建vo对象
                VideoVo videoVo = new VideoVo();
                //赋值
                BeanUtil.copyProperties(userInfo, videoVo);
                BeanUtil.copyProperties(video, videoVo);

                videoVo.setCover(video.getPicUrl());
                videoVo.setVideoUrl(video.getVideoUrl());
                videoVo.setSignature("左手右手一个慢动作");

                if (stringRedisTemplate.hasKey(StrUtil.format(ConstantUtil.FOCUS_USER, UserHolder.getId(), video.getUserId()))) {
                    videoVo.setHasFocus(1);
                }

                if (stringRedisTemplate.hasKey(StrUtil.format(ConstantUtil.VIDEO_LIKE, loginUserId, video.getId().toHexString()))) {
                    videoVo.setHasLiked(1);
                }

                //添加到集合
                videoVoList.add(videoVo);
            }
        }

        pageBeanVo.setItems(videoVoList);
        return pageBeanVo;
    }

    //上传小视频
    public void saveSmallVideos(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {
        //构建video
        Video video = new Video();
        video.setUserId(UserHolder.getId());
        video.setText("左手右手一个慢动作");

        //上传封面
        if (videoThumbnail != null && videoThumbnail.getSize() > 0) {
            String upload = ossTemplate.upload(System.currentTimeMillis() + videoThumbnail.getOriginalFilename(),
                    videoThumbnail.getInputStream());
            video.setPicUrl("https://" + upload);
        }

        //上传视频
        if (videoFile != null && videoFile.getSize() > 0) {
            StorePath storePath = client.uploadFile(videoFile.getInputStream(), videoFile.getSize(),
                    FileUtil.extName(videoFile.getOriginalFilename()), null);
            video.setVideoUrl(webServer.getWebServerUrl() + storePath.getFullPath());
        }



        videoService.saveVideo(video);

        videoMQManager.sendVideoMsg(video.getId().toHexString(), VideoMQManager.VIDEO_PUBLISH);
    }

    //关注
    public void saveUserFocus(Long videoUserId) {
        //获取当前用户id
        Long loginUserId = UserHolder.getId();
        //创建对象
        FocusUser focusUser = new FocusUser();
        //保存对象
        focusUser.setUserId(loginUserId);
        focusUser.setFocusUserId(videoUserId);

        focusUserService.saveFocus(focusUser);

        //放入缓存
        String key = StrUtil.format(ConstantUtil.FOCUS_USER, UserHolder.getId(), videoUserId);
        stringRedisTemplate.opsForValue().set(key, "1");
    }

    //取消关注
    public void removeUserUnFocus(Long videoUserId) {
        //取消关注
        focusUserService.removeFocus(UserHolder.getId(), videoUserId);
        String key = StrUtil.format(ConstantUtil.FOCUS_USER, UserHolder.getId(), videoUserId);

        //删除缓存
        stringRedisTemplate.delete(key);
    }

    //点赞
    public void saveLike(String videoId) {
        //获得当前用户id
        Long loginUserId = UserHolder.getId();
        //封装Comment对象
        Comment comment = new Comment();
        comment.setCreated(System.currentTimeMillis());
        comment.setPublishId(new ObjectId(videoId));
        comment.setCommentType(ConstantUtil.MOVEMENT_LIKE_4);
        comment.setUserId(loginUserId);

        //保存点赞操作
        commentService.saveLike(comment);



        String key = StrUtil.format(ConstantUtil.VIDEO_LIKE, loginUserId, videoId);
        stringRedisTemplate.opsForValue().set(key, "1");

        videoMQManager.sendVideoMsg(videoId,VideoMQManager.VIDEO_LIKE);
    }

    //视频取消点赞
    public void removeDisLike(String videoId) {
        //获得当前用户id
        Long loginUserId = UserHolder.getId();
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(videoId));
        comment.setCommentType(ConstantUtil.MOVEMENT_LIKE_4);
        comment.setUserId(loginUserId);

        //视频取消点赞
        commentService.removeDislike(comment);


        String key = StrUtil.format(ConstantUtil.VIDEO_LIKE, loginUserId, videoId);
        stringRedisTemplate.delete(key);

        videoMQManager.sendVideoMsg(videoId,VideoMQManager.VIDEO_DISLIKE);
    }

    //发布评论
    public void saveVideoComment(String videoId, String content) {
        //获取当前用户id
        Long loginUserId = UserHolder.getId();
        //封装Comment对象
        Comment comment = new Comment();
        comment.setCreated(System.currentTimeMillis());
        comment.setPublishId(new ObjectId(videoId));
        comment.setCommentType(ConstantUtil.MOVEMENT_LIKE_5);
        comment.setUserId(loginUserId);
        comment.setContent(content);



        commentService.saveComment(comment);

        videoMQManager.sendVideoMsg(videoId,VideoMQManager.VIDEO_COMMENT);
    }

    //查询评论列表
    public PageBeanVo findCommentList(String videoId, Integer page, Integer pageSize) {
        //获取当前用户id
        Long loginUserId = UserHolder.getId();

        PageBeanVo pageBeanVo = commentService.findVideoCommentList(page, pageSize, videoId);

        List<Comment> items = (List<Comment>) pageBeanVo.getItems();
        List<CommentVo> voList = new ArrayList<>();

        //数据搬家
        if (CollectionUtil.isNotEmpty(items)) {
            for (Comment comment : items) {
                //查询评论人信息
                UserInfo userInfo = userInfoService.findById(comment.getUserId());
                //封装CommentVo对象
                CommentVo commentVo = new CommentVo();
                BeanUtil.copyProperties(userInfo, commentVo);
                BeanUtil.copyProperties(comment, commentVo);
                commentVo.setCreateDate(DateFormatUtil.format(new Date(comment.getCreated())));

                if (stringRedisTemplate.hasKey(StrUtil.format(ConstantUtil.VIDEO_COMMENT_LIKE, loginUserId, comment.getId().toHexString()))) {
                    commentVo.setHasLiked(1);
                }

                voList.add(commentVo);
            }
        }

        pageBeanVo.setItems(voList);

        return pageBeanVo;
    }

    //评论点赞
    public void commentLike(String commentId) {
        //获取当前用户id
        Long loginUserId = UserHolder.getId();

        Comment comment = new Comment();
        comment.setCreated(System.currentTimeMillis());
        comment.setPublishId(new ObjectId(commentId));
        comment.setCommentType(ConstantUtil.MOVEMENT_LIKE_6);
        comment.setUserId(loginUserId);

        commentService.saveCommentLike(comment);

        String key = StrUtil.format(ConstantUtil.VIDEO_COMMENT_LIKE, loginUserId, commentId);
        stringRedisTemplate.opsForValue().set(key, "1");
    }

    //取消评论点赞
    public void commentDislike(String commentId) {
        //获取当前用户id
        Long loginUserId = UserHolder.getId();

        Comment comment = new Comment();
        comment.setCreated(System.currentTimeMillis());
        comment.setPublishId(new ObjectId(commentId));
        comment.setCommentType(ConstantUtil.MOVEMENT_LIKE_6);
        comment.setUserId(loginUserId);

        commentService.removeComment(comment);

        String key = StrUtil.format(ConstantUtil.VIDEO_COMMENT_LIKE, loginUserId, commentId);
        stringRedisTemplate.delete(key);
    }
}
